package com.example.daily.ui.statistics

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.patrykandpatrick.vico.compose.axis.horizontal.bottomAxis
import com.patrykandpatrick.vico.compose.axis.vertical.startAxis
import com.patrykandpatrick.vico.compose.chart.Chart
import com.patrykandpatrick.vico.compose.chart.column.columnChart
import com.patrykandpatrick.vico.compose.chart.line.lineChart
import com.patrykandpatrick.vico.compose.style.ProvideChartStyle
import com.patrykandpatrick.vico.core.entry.FloatEntry
import com.patrykandpatrick.vico.core.entry.entryModelOf
import java.time.Instant
import java.time.LocalDate
import java.time.ZoneId
import java.time.format.DateTimeFormatter

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun StatisticsScreen(
    viewModel: StatisticsViewModel = hiltViewModel()
) {
    val uiState by viewModel.uiState.collectAsState()
    val dateFormatter = DateTimeFormatter.ofPattern("MM-dd")

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("饮食统计") }
            )
        }
    ) { paddingValues ->
        if (uiState.isLoading) {
            Box(
                modifier = Modifier.fillMaxSize(),
                contentAlignment = Alignment.Center
            ) {
                CircularProgressIndicator()
            }
        } else if (uiState.error != null) {
            Box(
                modifier = Modifier.fillMaxSize(),
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = uiState.error!!,
                    color = MaterialTheme.colorScheme.error
                )
            }
        } else {
            LazyColumn(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(paddingValues)
                    .padding(16.dp),
                verticalArrangement = Arrangement.spacedBy(16.dp)
            ) {
                // 总览卡片
                item {
                    ElevatedCard {
                        Column(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(16.dp),
                            horizontalAlignment = Alignment.CenterHorizontally
                        ) {
                            Text(
                                text = "本周总览",
                                style = MaterialTheme.typography.titleLarge
                            )
                            Spacer(modifier = Modifier.height(8.dp))
                            Row(
                                modifier = Modifier.fillMaxWidth(),
                                horizontalArrangement = Arrangement.SpaceEvenly
                            ) {
                                Column(horizontalAlignment = Alignment.CenterHorizontally) {
                                    Text(
                                        text = "${uiState.totalCalories}",
                                        style = MaterialTheme.typography.headlineMedium
                                    )
                                    Text("总卡路里")
                                }
                                Column(horizontalAlignment = Alignment.CenterHorizontally) {
                                    Text(
                                        text = "${uiState.averageCalories}",
                                        style = MaterialTheme.typography.headlineMedium
                                    )
                                    Text("日均卡路里")
                                }
                            }
                        }
                    }
                }

                // 卡路里趋势图表
                item {
                    ElevatedCard {
                        Column(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(16.dp)
                        ) {
                            Text(
                                text = "卡路里趋势",
                                style = MaterialTheme.typography.titleMedium,
                                modifier = Modifier.padding(bottom = 16.dp)
                            )
                            
                            val entries = uiState.weeklyCalories.mapIndexed { index, daily ->
                                FloatEntry(
                                    x = index.toFloat(),
                                    y = daily.calories.toFloat()
                                )
                            }

                            ProvideChartStyle {
                                Chart(
                                    chart = lineChart(),
                                    model = entryModelOf(entries),
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .height(200.dp),
                                    startAxis = startAxis(),
                                    bottomAxis = bottomAxis(
                                        valueFormatter = { value, _ ->
                                            val index = value.toInt()
                                            if (index in uiState.weeklyCalories.indices) {
                                                LocalDate.parse(uiState.weeklyCalories[index].date)
                                                    .format(dateFormatter)
                                            } else ""
                                        }
                                    )
                                )
                            }
                        }
                    }
                }

                // 食物类型分布图表
                item {
                    ElevatedCard {
                        Column(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(16.dp)
                        ) {
                            Text(
                                text = "食物类型分布",
                                style = MaterialTheme.typography.titleMedium,
                                modifier = Modifier.padding(bottom = 16.dp)
                            )
                            
                            val entries = uiState.foodTypeDistribution.mapIndexed { index, data ->
                                FloatEntry(
                                    x = index.toFloat(),
                                    y = data.count.toFloat()
                                )
                            }

                            ProvideChartStyle {
                                Chart(
                                    chart = columnChart(),
                                    model = entryModelOf(entries),
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .height(200.dp),
                                    startAxis = startAxis(),
                                    bottomAxis = bottomAxis(
                                        valueFormatter = { value, _ ->
                                            val index = value.toInt()
                                            if (index in uiState.foodTypeDistribution.indices) {
                                                uiState.foodTypeDistribution[index].type
                                            } else ""
                                        }
                                    )
                                )
                            }
                        }
                    }
                }

                // 常见食物统计
                item {
                    ElevatedCard {
                        Column(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(16.dp)
                        ) {
                            Text(
                                text = "常见食物统计",
                                style = MaterialTheme.typography.titleMedium,
                                modifier = Modifier.padding(bottom = 16.dp)
                            )
                            uiState.mostFrequentFoods.forEach { food ->
                                Row(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(vertical = 4.dp),
                                    horizontalArrangement = Arrangement.SpaceBetween
                                ) {
                                    Column(modifier = Modifier.weight(1f)) {
                                        Text(text = food.foodName)
                                        Text(
                                            text = "食用 ${food.count} 次",
                                            style = MaterialTheme.typography.bodySmall,
                                            color = MaterialTheme.colorScheme.onSurfaceVariant
                                        )
                                    }
                                    Text(
                                        text = "${food.totalCalories} 卡路里",
                                        textAlign = TextAlign.End,
                                        modifier = Modifier.weight(1f)
                                    )
                                }
                                if (food != uiState.mostFrequentFoods.last()) {
                                    Divider(modifier = Modifier.padding(vertical = 4.dp))
                                }
                            }
                        }
                    }
                }

                // 体重变化图表
                item {
                    ElevatedCard {
                        Column(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(16.dp)
                        ) {
                            Text(
                                text = "体重变化趋势",
                                style = MaterialTheme.typography.titleMedium,
                                modifier = Modifier.padding(bottom = 16.dp)
                            )
                            
                            if (uiState.weightRecords.isEmpty()) {
                                Text(
                                    text = "暂无体重记录",
                                    style = MaterialTheme.typography.bodyMedium,
                                    modifier = Modifier.align(Alignment.CenterHorizontally)
                                )
                            } else {
                                val entries = uiState.weightRecords
                                    .sortedBy { it.recordDate }
                                    .mapIndexed { index, record ->
                                        FloatEntry(
                                            x = index.toFloat(),
                                            y = record.weight
                                        )
                                    }

                                ProvideChartStyle {
                                    Chart(
                                        chart = lineChart(),
                                        model = entryModelOf(entries.toList()),
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .height(200.dp),
                                        startAxis = startAxis(),
                                        bottomAxis = bottomAxis(
                                            valueFormatter = { value, _ ->
                                                val index = value.toInt()
                                                if (index in uiState.weightRecords.indices) {
                                                    Instant.ofEpochMilli(
                                                        uiState.weightRecords[index].recordDate
                                                    )
                                                        .atZone(ZoneId.systemDefault())
                                                        .toLocalDate()
                                                        .format(DateTimeFormatter.ofPattern("MM-dd"))
                                                } else ""
                                            }
                                        )
                                    )
                                }
                            }
                        }
                    }
                }
            }
        }
    }
} 